<template>
  <div class="orders-container">
    <div class="coffee-bg"></div>
    <div class="header-actions">
      <el-button type="primary" @click="handleCreateOrder">
        <i class="el-icon-plus"></i>新建订单
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索订单"
        style="width: 200px; margin-left: 16px">
        <template slot="prefix">
          <i class="el-icon-search"></i>
        </template>
      </el-input>
      <el-select v-model="statusFilter" placeholder="订单状态" style="width: 120px; margin-left: 16px">
        <el-option label="全部" value="" />
        <el-option label="待处理" value="pending" />
        <el-option label="制作中" value="preparing" />
        <el-option label="已完成" value="completed" />
        <el-option label="已取消" value="cancelled" />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 300px; margin-left: 16px"
      />
    </div>

    <el-table :data="filteredOrders" style="width: 100%; margin-top: 20px" class="coffee-table">
      <el-table-column prop="orderId" label="订单号" width="120" />
      <el-table-column prop="customerName" label="顾客姓名" width="120" />
      <el-table-column prop="items" label="商品">
        <template slot-scope="scope">
          <div v-for="item in scope.row.items" :key="item.id">
            {{ item.name }} x {{ item.quantity }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="总金额" width="120">
        <template slot-scope="scope">
          <span class="order-amount">¥{{ scope.row.totalAmount.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)" :class="scope.row.status === 'completed' ? 'coffee-tag' : ''">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="staff" label="处理员工" width="120" />
      <el-table-column label="操作" width="280">
        <template slot-scope="scope">
          <div class="action-buttons">
            <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              size="mini" 
              type="primary" 
              @click="handleUpdateStatus(scope.row)"
              v-if="scope.row.status !== 'completed' && scope.row.status !== 'cancelled'"
            >更新状态</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建订单对话框 -->
    <el-dialog
      :visible.sync="createOrderDialogVisible"
      title="新建订单"
      width="600px"
      class="coffee-dialog">
      <el-form :model="orderForm" :rules="rules" ref="orderFormRef" label-width="100px">
        <el-form-item label="顾客姓名" prop="customerName">
          <el-input v-model="orderForm.customerName" />
        </el-form-item>
        <el-form-item label="商品" prop="items">
          <div v-for="(item, index) in orderForm.items" :key="index" class="order-item">
            <el-select v-model="item.productId" placeholder="选择商品" style="width: 200px">
              <el-option
                v-for="product in products"
                :key="product.id"
                :label="product.name"
                :value="product.id"
              />
            </el-select>
            <el-input-number v-model="item.quantity" :min="1" style="margin-left: 10px" />
            <el-button type="danger" icon="el-icon-delete" circle @click="removeItem(index)" style="margin-left: 10px" />
          </div>
          <el-button type="primary" icon="el-icon-plus" @click="addItem" style="margin-top: 10px">添加商品</el-button>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="orderForm.note" :rows="3" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createOrderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrderSubmit">确定</el-button>
      </span>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      :visible.sync="viewOrderDialogVisible"
      title="订单详情"
      width="500px"
      class="coffee-dialog">
      <div v-if="selectedOrder" class="order-details">
        <p><strong>订单号：</strong>{{ selectedOrder.orderId }}</p>
        <p><strong>顾客姓名：</strong>{{ selectedOrder.customerName }}</p>
        <p><strong>创建时间：</strong>{{ selectedOrder.createTime }}</p>
        <p><strong>状态：</strong>
          <el-tag :type="getStatusType(selectedOrder.status)" :class="selectedOrder.status === 'completed' ? 'coffee-tag' : ''">
            {{ getStatusText(selectedOrder.status) }}
          </el-tag>
        </p>
        <p><strong>处理员工：</strong>{{ selectedOrder.staff }}</p>
        <p><strong>商品列表：</strong></p>
        <el-table :data="selectedOrder.items" style="width: 100%">
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="price" label="单价" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <p class="total-amount"><strong>总金额：</strong>¥{{ selectedOrder.totalAmount.toFixed(2) }}</p>
        <p v-if="selectedOrder.note"><strong>备注：</strong>{{ selectedOrder.note }}</p>
      </div>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      :visible.sync="updateStatusDialogVisible"
      title="更新订单状态"
      width="400px"
      class="coffee-dialog">
      <el-form :model="statusForm" ref="statusFormRef" label-width="100px">
        <el-form-item label="新状态" prop="status">
          <el-select v-model="statusForm.status">
            <el-option label="待处理" value="pending" />
            <el-option label="制作中" value="preparing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input type="textarea" v-model="statusForm.note" :rows="3" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateStatusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleStatusUpdateSubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  data() {
    return {
      searchQuery: '',
      statusFilter: '',
      dateRange: [],
      createOrderDialogVisible: false,
      viewOrderDialogVisible: false,
      updateStatusDialogVisible: false,
      selectedOrder: null,
      orderForm: {
        customerName: '',
        items: [],
        note: ''
      },
      statusForm: {
        status: '',
        note: ''
      },
      products: [],
      orders: [],
      rules: {
        customerName: [
          { required: true, message: '请输入顾客姓名', trigger: 'blur' }
        ],
        items: [
          { required: true, message: '请至少添加一个商品', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.loadProducts()
    this.loadOrders()
  },
  watch: {
    '$route'() {
      this.loadProducts()
      this.loadOrders()
    }
  },
  computed: {
    filteredOrders() {
      return this.orders.filter(order => {
        const matchSearch = order.orderId.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
                          order.customerName.toLowerCase().includes(this.searchQuery.toLowerCase())
        const matchStatus = !this.statusFilter || order.status === this.statusFilter
        const matchDate = !this.dateRange.length || (
          new Date(order.createTime) >= this.dateRange[0] &&
          new Date(order.createTime) <= this.dateRange[1]
        )
        return matchSearch && matchStatus && matchDate
      })
    }
  },
  methods: {
    loadProducts() {
      this.products = JSON.parse(localStorage.getItem('products') || '[]')
    },
    loadOrders() {
      this.orders = JSON.parse(localStorage.getItem('orders') || '[]')
    },
    getStatusType(status) {
      const types = {
        pending: 'warning',
        preparing: 'primary',
        completed: 'success',
        cancelled: 'info'
      }
      return types[status] || 'info'
    },
    getStatusText(status) {
      const texts = {
        pending: '待处理',
        preparing: '制作中',
        completed: '已完成',
        cancelled: '已取消'
      }
      return texts[status] || status
    },
    handleCreateOrder() {
      this.orderForm = {
        customerName: '',
        items: [],
        note: ''
      }
      this.createOrderDialogVisible = true
    },
    addItem() {
      this.orderForm.items.push({
        productId: '',
        quantity: 1
      })
    },
    removeItem(index) {
      this.orderForm.items.splice(index, 1)
    },
    handleCreateOrderSubmit() {
      this.$refs.orderFormRef.validate(valid => {
        if (!valid) return
        
        const items = this.orderForm.items.map(item => {
          const product = this.products.find(p => p.id === item.productId)
          return {
            id: product.id,
            name: product.name,
            quantity: item.quantity,
            price: product.price
          }
        })
        
        const totalAmount = items.reduce((sum, item) => sum + item.price * item.quantity, 0)
        
        const newOrder = {
          orderId: `ORD${String(this.orders.length + 1).padStart(3, '0')}`,
          customerName: this.orderForm.customerName,
          items,
          totalAmount,
          status: 'pending',
          createTime: new Date().toLocaleString(),
          staff: '待分配',
          note: this.orderForm.note
        }
        
        this.orders.push(newOrder)
        localStorage.setItem('orders', JSON.stringify(this.orders))
        this.$message.success('订单创建成功')
        this.createOrderDialogVisible = false
        this.addOperationLog('创建订单', `订单号:${newOrder.orderId} 顾客:${newOrder.customerName}`)
      })
    },
    handleView(order) {
      this.selectedOrder = order
      this.viewOrderDialogVisible = true
    },
    handleUpdateStatus(order) {
      this.selectedOrder = order
      this.statusForm = {
        status: order.status,
        note: ''
      }
      this.updateStatusDialogVisible = true
    },
    handleStatusUpdateSubmit() {
      if (!this.statusForm.status) {
        this.$message.warning('请选择新状态')
        return
      }
      
      const index = this.orders.findIndex(o => o.orderId === this.selectedOrder.orderId)
      this.orders[index].status = this.statusForm.status
      localStorage.setItem('orders', JSON.stringify(this.orders))
      this.$message.success('状态更新成功')
      this.updateStatusDialogVisible = false
      this.addOperationLog('更新订单状态', 
        `订单号:${this.selectedOrder.orderId} 新状态:${this.getStatusText(this.statusForm.status)}`)
    },
    handleDelete(row) {
      this.$confirm('确定要删除这个订单吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.orders = this.orders.filter(item => item.orderId !== row.orderId)
        localStorage.setItem('orders', JSON.stringify(this.orders))
        this.$message.success('删除成功')
        this.addOperationLog('删除订单', `订单号:${row.orderId} 顾客:${row.customerName}`)
      }).catch(() => {
        // 用户点击取消按钮时，不执行任何操作
      })
    },
    addOperationLog(action, detail) {
      const user = JSON.parse(localStorage.getItem('adminUser') || '{}')
      const logs = JSON.parse(localStorage.getItem('operationLogs') || '[]')
      logs.push({
        time: new Date().toLocaleString(),
        user: user.username || '未知',
        action,
        detail
      })
      localStorage.setItem('operationLogs', JSON.stringify(logs))
    }
  }
}
</script>

<style scoped>
.orders-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #e7d2ba 0%, #b08968 100%);
  position: relative;
  overflow: hidden;
}
.coffee-bg {
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  z-index: 0;
  pointer-events: none;
  background: url('https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/2615.png') repeat 0 0/120px auto;
  opacity: 0.06;
}
.header-actions {
  display: flex;
  align-items: center;
  z-index: 1;
}
.el-button--primary {
  background: linear-gradient(90deg, #a47149 0%, #7c4f22 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(124, 79, 34, 0.08);
  transition: background 0.2s;
}
.el-button--primary:hover {
  background: linear-gradient(90deg, #7c4f22 0%, #a47149 100%);
}
.el-input__inner {
  background: #f8f5f2;
  border-radius: 8px;
  border: 1px solid #e0c3a0;
}
.el-select .el-input__inner {
  background: #f8f5f2;
  border-radius: 8px;
  border: 1px solid #e0c3a0;
}
.coffee-table {
  background: rgba(255,255,255,0.96);
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(124, 79, 34, 0.08);
  overflow: hidden;
}
.coffee-table th, .coffee-table td {
  background: transparent !important;
}
.coffee-tag {
  background: #e7d2ba !important;
  color: #7c4f22 !important;
  border: none !important;
}
.order-amount {
  color: #a47149;
  font-weight: bold;
}
.order-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.order-details {
  padding: 20px;
}
.order-details p {
  margin: 10px 0;
}
.total-amount {
  font-size: 18px;
  color: #a47149;
  margin-top: 20px;
  font-weight: bold;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}
.el-button--mini {
  padding: 7px 12px;
  border-radius: 6px;
}
.coffee-dialog .el-dialog {
  border-radius: 16px;
  box-shadow: 0 4px 18px 0 rgba(124, 79, 34, 0.10);
  border: 1px solid #e0c3a0;
  background: rgba(255, 255, 255, 0.98);
}
</style> 